<template>
  <div class="page-controller">
    <organization @on-cell-change="onCellChange" ref="childComp" @select-single-data="selectClick"></organization>
    <div class="page-form">
      <FISearchForm
        class="box-radius2"
        ref="ruleFormRef"
        :id="`inqu_${tableId}`"
        :searchNum="searchItemCount"
        v-model:form-value="state.query"
        :table-column="columns"
        :wrapperSpan="searchWrapperSpan"
        @submit="searchFn"
      >
        <el-col :span="searchWrapperSpan" class="flex-center">
          <FIFormItem prop="treeEname" label="节点树编码">
            <FIInput v-model="state.query.treeEname" clearable />
          </FIFormItem>
        </el-col>
        <el-col :span="searchWrapperSpan" class="flex-center">
          <FIFormItem name="nodeEname" label="节点编码">
            <FIInput v-model="state.query.nodeEname" clearable />
          </FIFormItem>
        </el-col>
        <el-col :span="searchWrapperSpan" class="flex-center">
          <FIFormItem name="nodeCname" label="节点名称">
            <FIInput v-model="state.query.nodeCname" clearable />
          </FIFormItem>
        </el-col>
        <el-col :span="searchWrapperSpan" class="flex-center">
          <FIFormItem name="nodeType" label="节点类型">
            <FISelect
              v-model="state.query.nodeType"
              valueCustom="value"
              :options="[
                { value: '1', label: '页面' },
                { value: '2', label: '目录' },
              ]"
              clearable
            />
          </FIFormItem>
        </el-col>
      </FISearchForm>
      <div class="margin-bottom20"></div>
      <FITable
        ref="tableRef"
        class="box-radius2"
        title="菜单管理列表"
        :id="`result_${tableId}`"
        :readonly="false"
        :data="state.dataList"
        primaryKey="nodeId"
        v-model:columns="columns"
        :isLoading="isTableLoading"
        insertable
        deletable
        :saveSuccessful="saveSuccessful"
        :pageConfig="pageConfig"
        @row-add-save="addRowSave"
        @table-refresh="searchFn"
        @selection-change="handleSelectionChange"
        @size-change="handleSizeChange"
        @current-page-change="handleCurrentChange"
        @row-add="onAddRow"
        @row-delete="deleteRow"
      >
        <template #headerBtn>
          <!-- <FIButton id="b3333"></FIButton> -->
          <!-- <FIPopconfirmBtn
            title="您是否确认删除选中数据吗？"
            
            beforePopText="请选择一条数据"
            :btn-binds="{ id:'delete' }"
            :isVisible="!!checkedRows.length"
            @confirm="deleteRow"
          >
          </FIPopconfirmBtn> -->
          <FIPopconfirmBtn
            :class="!!checkedRows.length ? 'margin-right12' : ''"
            title="您是否确认删除选中数据吗？"
            buttonText="递归删除"
            beforePopText="请选择一条数据"
            :btn-binds="{ border: true, prefixIcon: 'icon-shanchu' }"
            :isVisible="!!checkedRows.length"
            @confirm="deleteRow1"
          >
          </FIPopconfirmBtn>
          <!-- <FIPopconfirmBtn
            title="您是否确认删除选中数据吗？"
            buttonText="删除"
            beforePopText="请选择一条数据"
            :btn-binds="{ border: true, prefixIcon: 'icon-shanchu' }"
            :isVisible="!!checkedRows.length"
            @confirm="deleteRow"
          >
          </FIPopconfirmBtn> -->
        </template>
        <template #headerBtnRight>
          <FIPopconfirmBtn
            style="margin-left: 12px"
            title="您是否确认要刷新缓存？"
            buttonText="刷新缓存"
            api-url="/rm2/menuMaint/refreshCache"
            :btn-binds="{ border: true }"
          >
          </FIPopconfirmBtn>
        </template>
      </FITable>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, computed, watch, PropType } from 'vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIButton from '@/components/FIButton.vue'
import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
import FITable from '@/components/FITable/index.vue'
import FISelect from '@/components/FISelect/index.vue'
import { apiRequestPost } from '@/api/globalApi.js'
import {
  apiGetmenuMaintQuery,
  apiGetmenuMaintSave,
  apiGetmenuMaintDel,
  apideleteRecurs,
} from '@/api/configEnvMaint/index.ts'
import { ElMessage } from 'element-plus'
import { useMessage } from '@/hooks/message'
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import organization from './components/organization.vue'
const props = defineProps({
  // 表单类型，修改: moidify  添加: add
  type: {
    type: String as PropType<'modify' | 'add' | 'info'>,
    default: 'info',
    required: true,
    validator(value: string) {
      return ['modify', 'add', 'info'].includes(value)
    },
  },
  // 当前点击的level层级
  level: {
    type: [Number, String] as PropType<number | string>,
    default: 1,
    required: true,
    validator(value: number | string) {
      return typeof value === 'string' || (typeof value === 'number' && value >= 1 && value <= 4)
    },
  },
  //  选中节点对象
  nodeInfo: {
    type: Object,
    required: true,
  },
})
const childComp = ref(null)
const route = useRoute()

const searchWrapperSpan = 8
const showSearch = ref(true)
const isTableLoading = ref(false)
// 页面编码
const tableId = 'menuMaint'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
const tableRef = ref(null)

const state = reactive({
  query: {
    treeEname: '',
    nodeEname: '',
    nodeCname: '',
    nodeType: '',
    dynamicParams: [],
    orderbyParams: [],
    current: 1,
    size: 10,
  },
  dataList: [],
})
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
  pageSizes: [10, 20, 50, 100],
})
const jdsbm = ref('')
const columns: Column[] = reactive([
  // {
  //   label: '节点ID',
  //   prop: 'nodeId',
  //   align: 'center',
  //   width: '120',
  //   editable: false,
  //   editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  // },

  {
    label: '节点树编码',
    prop: 'treeEname',
    queryName: 'tedfa00.form_Cname',
    align: 'center',
    width: '150',
    editType: 'input',
    editable: true,
    required: true,
    readonly: true,
    // filterable: true,
    // sortable: true,
    sortValue: '',
    modelValue: { inputValue: '' },
    editConfig: {
      rules: { treeEname: [{ required: true, message: '请输入节点树编码', trigger: 'blur' }] },
    },
  },
  {
    label: '节点编码',
    prop: 'nodeEname',
    queryName: 'tedfa00.form_Cname',
    align: 'center',
    readonly: true,
    width: '150',
    editType: 'input',
    editable: true,
    required: true,
    readonly: true,
    // sortable: true,
    sortValue: '',
    modelValue: { inputValue: '' },
    editConfig: {
      rules: { nodeEname: [{ required: true, message: '请输入节点编码', trigger: 'blur' }] },
    },
  },
  {
    label: '节点名称',
    prop: 'nodeCname',
    queryName: 'tedfa00.form_Cname',
    align: 'center',
    width: '150',
    editType: 'input',
    editable: true,
    required: true,
    // filterable: true,
    // sortable: true,
    sortValue: '',
    modelValue: { inputValue: '' },
    editConfig: {
      rules: { nodeCname: [{ required: true, message: '请输入节点名称', trigger: 'blur' }] },
    },
  },
  {
    label: '节点类型',
    prop: 'nodeType',
    align: 'center',
    width: '130',
    editable: true,
    required: true,
    // filterable: true,
    // sortable: true,
    editType: 'select',
    modelValue: [],
    editConfig: {
      rules: { nodeType: [{ required: true, message: '请输入类型', trigger: 'blur' }] },
      // options: [
      //   { value: '1', label: '页面' },
      //   { value: '2', label: '目录' },
      // ],
      options: [
        { value: 1, label: '页面' },
        { value: 2, label: '目录' },
      ],
      selectBinds: {
        multiple: false,
        valueCustom: 'value',
      },
    },
  },
  {
    label: '图标',
    prop: 'nodeImagePath',
    align: 'center',
    width: '180',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    editable: true,
    // filterable: true,
    modelValue: { inputValue: '' },
    // sortable: true,
    sortValue: '',
    editConfig: {
      rules: { formLoadPath: [{ required: false, message: '请输入图标', trigger: 'blur' }] },
    },
  },
  {
    label: '参数',
    prop: 'nodeParam',
    align: 'center',
    width: '180',
    editable: true,
    // filterable: true,
    // sortable: true,
    modelValue: { inputValue: '' },
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    // editConfig: {
    //   rules: { nodeParam: [{ required: true, message: '请输入参数', trigger: 'blur' }] },
    // },
  },
  {
    label: '排序',
    prop: 'nodeSortId',
    align: 'center',
    width: '180',
    editable: true,
    // filterable: true,
    sortable: false,
    modelValue: { inputValue: '' },
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    // editConfig: {
    //   rules: { nodeParam: [{ required: true, message: '请排序', trigger: 'blur' }] },
    // },
  },

  {
    label: '页面载入路径',
    prop: 'nodeUrl',
    align: 'center',
    width: '180',
    editable: true,
    // filterable: true,
    // sortable: true,
    editType: 'select',
    modelValue: [],
    configValueToLable: {
      list: [
        { value: '1', label: '启用' },
        { value: '0', label: '禁用' },
      ],
    },
    editConfig: {
      // rules: { nodeUrl: [{ required: true, message: '请输入路径', trigger: 'blur' }] },
      options: [
        { value: '1', label: '启用' },
        { value: '0', label: '禁用' },
      ],
      selectBinds: {
        multiple: false,
        valueCustom: 'value',
      },
    },
  },
  {
    label: '创建人',
    prop: 'recCreator',
    align: 'center',
    width: '120',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '创建时间',
    prop: 'recCreateTime',
    align: 'center',
    width: '160',
    editType: 'time-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '修改人',
    prop: 'recRevisor',
    align: 'center',
    width: '120',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '修改时间',
    prop: 'recReviseTime',
    align: 'center',
    width: '160',
    editType: 'date-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
])

const checkedRows = ref([])
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn('page')
}
// 隐藏搜索项有值的个数
const searchItemCount = computed(() => {
  let filledCount = 0
  const outKeys = ['dynamicParams', 'orderbyParams', 'size', 'current']
  // 下面是从第三项起计算常规搜索条件有值个树
  // 获取state.query的所有keys
  const queryKeys = Object.keys(state.query).filter((key) => !outKeys.includes(key))
  if (queryKeys.length < 3) return 0
  // 从第三项开始计算
  queryKeys.slice(2).forEach((key) => {
    if (state.query[key] !== '' && state.query[key] !== null) {
      filledCount++
    }
  })
  return filledCount
})
const onAddRow = () => {
  console.log(jdsbm.value, 1111)

  // treeEname:jdsbm.value, // 这里设置你想要的默认值
  // 其他列的初始值，根据需要添加
  // column2: '',
  // column3: '',
  // tableRef.value.cloneTableData[0].treeEname=jdsbm.value

  // tableRef.value.cloneTableData.push(newRow)
  // 如果表格已经有数据，我们需要找到最后一行
  const lastRowIndex = tableRef.value.cloneTableData.length - 1

  // 检查是否已有数据，如果无数据则创建新行
  if (lastRowIndex === -1) {
    // 创建新行
    tableRef.value.cloneTableData.push({
      treeEname: jdsbm.value, // 给treeEname赋值
      // 其他列的初始值，根据需要添加
      // column2: '',
      // column3: '',
    })
  } else {
    // 如果已有数据，直接修改最后一行的treeEname
    tableRef.value.cloneTableData[lastRowIndex].treeEname = jdsbm.value
  }
}
const selectClick = (data) => {
  state.query.treeEname = data
  searchFn()
}
const searchFn = (type?: string, columnsVal?: any) => {
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns

  if(type == 'page'){
    state.query.current = pageConfig.currentPage
  }else{
    pageConfig.currentPage = 1
    state.query.current = 1
  }
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  console.log(state.query, '查看state.query')
  apiGetmenuMaintQuery(state.query)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        state.dataList = res.data.data.result
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      } else {
        // ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const handleSave = () => {
  isTableLoading.value = true
  saveSuccessful.value = false
  apiGetmenuMaintSave(checkedRows.value)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        // saveSuccessful.value = true
        searchFn()
        useMessage().success(res.data.message)
        tableRef.value.clearSelection()
        childComp.value.refreshTreeNode()
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
  //
}
const deleteRow = () => {
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  let ids = []
  Array.isArray(checkedRows.value) &&
    checkedRows.value.forEach((item: any) => {
      if (item?.nodeId) ids.push(item?.nodeId)
    })
  isTableLoading.value = true
  console.log(ids)
  apiGetmenuMaintDel(ids)
    .then((res) => {
      isTableLoading.value = false
      searchFn()
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const deleteRow1 = () => {
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  let ids = []
  Array.isArray(checkedRows.value) &&
    checkedRows.value.forEach((item: any) => {
      if (item?.nodeId) ids.push(item?.nodeId)
    })
  isTableLoading.value = true
  apideleteRecurs(ids)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        useMessage().success(res.data.message)
        searchFn()
        childComp.value.refreshTreeNode()
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const ruleFormRef = ref(null)

const addRowSave = (data) => {
  handleSave(data, 'add')
}
const onCellChange = (e, nodeData) => {
  console.log(e, nodeData)
  state.query.treeEname = e.nodeEname
  if (e.label == '系统平台') {
    jdsbm.value = 'root'
  } else {
    jdsbm.value = e.nodeEname
  }
  searchFn()
}
watch(
  () => columns.values,
  (newValue) => {},
  { deep: true } // 开启深度监听，因为数组或对象内部属性的改变浅层监听可能无法捕获
)
watch(
  () => childComp.value,
  () => {
    initRuleForm()
    console.log('wsj111111111111----', state.query, props.nodeInfo, props.level)
  },
  { deep: true }
)
const initRuleForm = () => {
  console.log(childComp.value, 1111111111111)
  let infoObj = props.nodeInfo
  if (props.type === 'add') {
    if (props.level == 1) {
      state.query = {
        // projectCname: '',
        // language: '',
        // routePath: '',
        // projectDesc: '',
        treeEname: 'root',
        nodeEname: '',
        nodeCname: '',
        nodeType: '',
        dynamicParams: [],
        orderbyParams: [],
        current: 1,
        size: 10,
      }
    } else {
      if (props.level == 2) {
        state.query = {
          // projectEname: infoObj?.projectEname,
          // moduleEname1: infoObj?.moduleEname1,
          // moduleCname1: infoObj?.moduleCname1,
          treeEname: infoObj?.treeEname,
          nodeEname: '',
          nodeCname: '',
          nodeType: '',
          dynamicParams: [],
          orderbyParams: [],
          current: 1,
          size: 10,
        }
      } else if (props.level == 3) {
        state.query = {
          // moduleEname1: infoObj?.moduleEname1,
          // moduleEname2: infoObj?.moduleEname2,
          // moduleCname2: infoObj?.moduleCname2,
          treeEname: infoObj?.treeEname,
          nodeEname: '',
          nodeCname: '',
          nodeType: '',
          dynamicParams: [],
          orderbyParams: [],
          current: 1,
          size: 10,
        }
      }
    }
  } else {
    if (props.level == 2) {
      state.query = {
        // projectEname: infoObj?.projectEname,
        // projectCname: infoObj?.projectCname,
        // language: infoObj?.language,
        // routePath: infoObj?.routePath,
        // projectDesc: infoObj?.projectDesc,
        treeEname: infoObj?.treeEname,
        nodeEname: '',
        nodeCname: '',
        nodeType: '',
        dynamicParams: [],
        orderbyParams: [],
        current: 1,
        size: 10,
      }
    } else if (props.level == 3) {
      state.query = {
        // projectEname: infoObj?.projectEname,
        // moduleEname1: infoObj?.moduleEname1,
        // moduleCname1: infoObj?.moduleCname1,
        treeEname: infoObj?.treeEname,
        nodeEname: '',
        nodeCname: '',
        nodeType: '',
        dynamicParams: [],
        orderbyParams: [],
        current: 1,
        size: 10,
      }
    } else if (props.level == 4) {
      state.query = {
        // moduleEname1: infoObj?.moduleEname1,
        // moduleEname2: infoObj?.moduleEname2,
        // moduleCname2: infoObj?.moduleCname2,
        treeEname: infoObj?.treeEname,
        nodeEname: '',
        nodeCname: '',
        nodeType: '',
        dynamicParams: [],
        orderbyParams: [],
        current: 1,
        size: 10,
      }
    }
  }
}
onMounted(() => {
  initRuleForm()
  // 获取查询条件缓存
  const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  if (columns) columns.values = cachedColumns
  // searchFn()
})
</script>
<style lang="less" scoped>
.page-controller {
  width: 100%;
  display: flex;

  .page-form {
    // flex: 1;
    width: calc(100% - 310px);
    margin: 0 20px;
  }
}
::v-deep(.el-dropdown-menu__item) {
  padding: 5px 16px;
  border-radius: 2px;
  margin: 4px;
}
.page-tree {
  // width: 228px;
  width: 300px;
  //   min-height: calc(100vh - 175px);
  // padding: 16px;
  .page-tree__title {
    font-size: 16px;
    color: #303133;
    line-height: 28px;
    text-align: left;
    font-weight: bold;
  }
  .page-tree__line {
    margin: 16px -16px;
    height: 1px;
    background: #e8e8e8;
    width: calc(100% + 32px);
  }
  .page-tree__search {
    margin-bottom: 18px;
  }
  .custom-tree-node {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 32px;
    padding-right: 5px;
    position: relative;
    &-label {
      width: calc(100% - 20px);
      // width: 100%;
      text-align: left;
      // padding-right: 60px;
    }
    // &-label3 {
    //   width: calc(100% - 50px);
    //   // width: 100%;
    //   text-align: left;
    //   // padding-right: 60px;
    // }
    // &-label4 {
    //   width: calc(100% - 70px);
    //   // width: 100%;
    //   text-align: left;
    //   // padding-right: 60px;
    // }
    &-add {
      position: absolute;
      right: 5px;
      top: 8px;
      color: var(--el-color-primary-light-2);
    }
  }
  .custom-tree-node3 {
    width: calc(100% - 30px);
  }
  .custom-tree-node4 {
    width: calc(100% - 30px);
  }
  ::v-deep(.el-tree-node__content) {
    height: 32px;
    border-radius: 2px;
    .el-tree-node__expand-icon {
      color: #989898;
    }
  }
}
</style>
